Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 7x 1x 1x 3x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { NextRequest, NextResponse } from 'next/server';
import {
withAuth,
withErrorHandling,
successResponse,
validationErrorResponse,
ApiError,
ApiSuccessResponse,
ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { updateCartItemSchema, validateInput } from "@/lib/validation-schemas";
import { Session } from "next-auth";
// PATCH /api/cart/[id] - Update cart item quantity
async function handlePatch(
request: NextRequest,
context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
const { id } = await context!.params!;
const productId = parseInt(id);
const body = await request.json();
const userId = session.user.id;
// Validate input
const validation = validateInput(updateCartItemSchema, body);
if (!validation.success) {
return validationErrorResponse("Validation failed", validation.errors);
}
const { quantity } = validation.data!;
// Find cart item
const cartItem = await prisma.cart.findUnique({
where: {
userId_productId: {
userId,
productId}}});
if (!cartItem) {
throw ApiError.notFound("Cart item");
}
const deviceId = request.headers.get("x-device-id") || "default";
// Update quantity and sync info
const updatedCartItem = await prisma.cart.update({
where: { id: cartItem.id },
data: {
quantity,
deviceId,
syncedAt: new Date()},
include: {
product: {
include: {
images: true}}}});
return successResponse(updatedCartItem);
}
// DELETE /api/cart/[id] - Remove item from cart
async function handleDelete(
request: NextRequest,
context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<{ message: string }>>> {
const { id } = await context!.params!;
const productId = parseInt(id);
const userId = session.user.id;
// Find and delete cart item
const cartItem = await prisma.cart.findUnique({
where: {
userId_productId: {
userId,
productId}}});
if (!cartItem) {
throw ApiError.notFound("Cart item");
}
await prisma.cart.delete({
where: { id: cartItem.id }});
return successResponse({ message: "Cart item removed successfully" });
}
export const PATCH = withErrorHandling(withAuth(handlePatch));
export const DELETE = withErrorHandling(withAuth(handleDelete));
|